package com.daluzy.chmanager.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.cazaea.sweetalert.SweetAlertDialog;
import com.daluzy.chmanager.MyApplication;
import com.daluzy.chmanager.R;
import com.daluzy.chmanager.bean.Account;
import com.daluzy.chmanager.bean.Manager;
import com.daluzy.chmanager.bean.School;
import com.daluzy.chmanager.bean.Students;
import com.daluzy.chmanager.util.TelephoneUtil;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

/**
 * 添加管理员
 */
public class AddStudentActivity extends AppCompatActivity {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.et_student_name)
    EditText etStudentName;
    @BindView(R.id.et_student_num)
    EditText etStudentNum;
    @BindView(R.id.et_student_phone)
    EditText etStudentPhone;
    @BindView(R.id.radio_btn_male)
    RadioButton radioBtnMale;
    @BindView(R.id.radio_btn_female)
    RadioButton radioBtnFemale;
    @BindView(R.id.radio_group_sex)
    RadioGroup radioGroupSex;
    @BindView(R.id.et_student_grade)
    EditText etStudentGrade;
    @BindView(R.id.et_student_speciality)
    EditText etStudentSpeciality;
    @BindView(R.id.et_student_place)
    EditText etStudentPlace;
    @BindView(R.id.et_student_class)
    EditText etStudentClass;
    @BindView(R.id.et_student_department)
    EditText etStudentDepartment;
    @BindView(R.id.tv_add_commit)
    TextView tvAddCommit;
    @BindView(R.id.tv_student_school)
    TextView tvStudentSchool;
    private School school;

    private LoadingDialog loadingDialog;
    private String studentSex = "男";
    private int type = 0;
    private Students students;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_studeng_daluzy);
        ButterKnife.bind(this);
        type = getIntent().getIntExtra("type", 0);
        if (type == 1) {
            tvTitle.setText("学生信息修改");
            tvAddCommit.setText("确认修改");
            etStudentName.setEnabled(false);
            students = (Students) getIntent().getSerializableExtra("students");
            if (students.getStudent_sex().equals("男")) {
                radioGroupSex.check(R.id.radio_btn_male);
            } else {
                radioGroupSex.check(R.id.radio_btn_female);
            }
            etStudentName.setText(students.getStudent_name());
            etStudentClass.setText(students.getStudent_class());
            etStudentDepartment.setText(students.getStudent_department());
            etStudentGrade.setText(students.getStudent_grade());
            etStudentNum.setText(students.getStudent_id());
            etStudentPhone.setText(students.getStudent_phone());
            etStudentPlace.setText(students.getStudent_place());
            etStudentSpeciality.setText(students.getStudent_speciality());

            etStudentName.setOnClickListener(v -> Toast.makeText(AddStudentActivity.this,"学生姓名无法修改",Toast.LENGTH_SHORT).show());
        } else {
            tvTitle.setText("新增学生信息");
            tvAddCommit.setText("添加");
            radioGroupSex.check(R.id.radio_btn_male);
        }

        loadingDialog = new LoadingDialog(this);


        radioGroupSex.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.radio_btn_male) {
                    studentSex = "男";
                } else {
                    studentSex = "女";
                }
            }
        });
    }

    @OnClick({R.id.iv_back, R.id.tv_student_school, R.id.tv_add_commit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_student_school:
                Intent intent = new Intent(AddStudentActivity.this, SelectSchoolActivity.class);
                startActivityForResult(intent, 2021);
                break;
            case R.id.tv_add_commit:
                tvAddCommit.setEnabled(false);
                studentCheck();
                break;
        }
    }

    Account account;

    private void studentCheck() {

        String studentName = etStudentName.getText().toString().trim();
        String studentNum = etStudentNum.getText().toString().trim();
        String studentGrade = etStudentGrade.getText().toString().trim();
        String studentSpe = etStudentSpeciality.getText().toString().trim();
        String studentPlace = etStudentPlace.getText().toString().trim();
        String studentClass = etStudentClass.getText().toString().trim();
        String studentDepartment = etStudentDepartment.getText().toString().trim();
        String studentPhone = etStudentPhone.getText().toString().trim();

        if (TextUtils.isEmpty(studentName)) {
            Toast.makeText(AddStudentActivity.this, "请输入姓名", Toast.LENGTH_SHORT).show();
            tvAddCommit.setEnabled(true);
            return;
        }
        if (TextUtils.isEmpty(studentNum)) {
            Toast.makeText(AddStudentActivity.this, "请输入学号", Toast.LENGTH_SHORT).show();
            tvAddCommit.setEnabled(true);
            return;
        }
        if (TextUtils.isEmpty(studentPhone)) {
            Toast.makeText(AddStudentActivity.this, "请输入电话号码", Toast.LENGTH_SHORT).show();
            tvAddCommit.setEnabled(true);
            return;
        }

        if (!TelephoneUtil.checkCellphone(studentPhone)) {
            Toast.makeText(AddStudentActivity.this, "请输入正确的电话号码", Toast.LENGTH_SHORT).show();
            tvAddCommit.setEnabled(true);
            return;
        }

        if (TextUtils.isEmpty(studentGrade)) {
            Toast.makeText(AddStudentActivity.this, "请输入所在年级", Toast.LENGTH_SHORT).show();
            tvAddCommit.setEnabled(true);
            return;
        }
        if (TextUtils.isEmpty(studentSpe)) {
            Toast.makeText(AddStudentActivity.this, "请输入所学专业", Toast.LENGTH_SHORT).show();
            tvAddCommit.setEnabled(true);
            return;
        }
        if (TextUtils.isEmpty(studentPlace)) {
            Toast.makeText(AddStudentActivity.this, "请输入籍贯", Toast.LENGTH_SHORT).show();
            tvAddCommit.setEnabled(true);
            return;
        }
        if (TextUtils.isEmpty(studentClass)) {
            Toast.makeText(AddStudentActivity.this, "请输入所在班", Toast.LENGTH_SHORT).show();
            tvAddCommit.setEnabled(true);
            return;
        }
        if (TextUtils.isEmpty(studentDepartment)) {
            Toast.makeText(AddStudentActivity.this, "请输入所在院系", Toast.LENGTH_SHORT).show();
            tvAddCommit.setEnabled(true);
            return;
        }

        if (loadingDialog != null) {
            loadingDialog.show();
        }
        if (type != 1)
            students = new Students();
        students.setAccount(studentPhone);
        students.setStudent_class(studentClass);
        students.setStudent_department(studentDepartment);
        students.setStudent_grade(studentGrade);
        students.setStudent_id(studentNum);
        students.setStudent_name(studentName);
        students.setStudent_phone(studentPhone);
        students.setStudent_place(studentPlace);
        students.setStudent_sex(studentSex);
        students.setStudent_speciality(studentSpe);

        if (school != null) {
            students.setStudent_school(String.valueOf(school.getSchool_id()));
        } else {
            if (type != 1) {
                Toast.makeText(AddStudentActivity.this, "请选择学校", Toast.LENGTH_SHORT).show();
                tvAddCommit.setEnabled(true);
                return;
            }
        }
        if (type == 1) {
            updateStudent();
        } else {
            account = new Account();
            account.setAccount(studentPhone);
            account.setPassword("123456");
            checkAccount();
        }
    }

    private void updateStudent() {
        students.update(students.getObjectId(), new UpdateListener() {

            @Override
            public void done(BmobException e) {
                if (e == null) {
                    MyApplication.getIntance().setStudents(students);
                    Toast.makeText(AddStudentActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                    finish();
                } else {
                    Toast.makeText(AddStudentActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }

        });
    }

    private void checkAccount() {
        if (loadingDialog != null)
            loadingDialog.show();
        BmobQuery<Account> query = new BmobQuery<>();
        query.addWhereEqualTo("account", students.getAccount());
        query.order("-createdAt")
                .findObjects(new FindListener<Account>() {
                    @Override
                    public void done(List<Account> object, BmobException e) {
                        if (e == null) {
                            if (object != null && object.size() > 0) {
                                final SweetAlertDialog mDialog = new SweetAlertDialog(AddStudentActivity.this, SweetAlertDialog.NORMAL_TYPE)
                                        .setTitleText("提示")
                                        .setContentText("该账号已存在，是否直接绑定？")
                                        .setCustomImage(null)
                                        .setCancelText("否")
                                        .setConfirmText("是")
                                        .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                            @Override
                                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                                sweetAlertDialog.dismiss();
                                                if (loadingDialog != null)
                                                    loadingDialog.close();
                                            }
                                        }).setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                            @Override
                                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                                sweetAlertDialog.dismiss();
                                                addStudent();
                                            }
                                        });
                                mDialog.show();
                            } else {
                                addAccount();
                            }

                        } else {
                            Toast.makeText(AddStudentActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                            if (loadingDialog != null)
                                loadingDialog.close();
                        }
                        tvAddCommit.setEnabled(true);
                    }
                });
    }

    private void addAccount() {
        account.save(new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                if (e == null) {
                    addStudent();
                } else {
                    Toast.makeText(AddStudentActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                    if (loadingDialog != null)
                        loadingDialog.close();
                }

            }
        });
    }

    private void addStudent() {
        students.save(new SaveListener<String>() {
            @Override
            public void done(String objectId, BmobException e) {
                if (e == null) {
                    Toast.makeText(AddStudentActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
                    finish();
                } else {
                    Toast.makeText(AddStudentActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                }
                if (loadingDialog != null)
                    loadingDialog.close();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 2021 && resultCode == 2021) {
            school = (School) data.getSerializableExtra("school");
            if (school != null)
                tvStudentSchool.setText(school.getSchool_name());
        }
    }
}
